<template>
    <el-container class="schedule-page">
    <!-- 左侧导航栏 -->
    <el-aside width="200px" class="aside">
      <div class="profile">
        <el-avatar :size="60" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
      </div>
      <el-menu :default-active="activeMenu" @select="handleMenuSelect">
        <el-menu-item index="schedule">
          <div class="menu-item-content">
            <i class="el-icon-date icon"></i>
            <span class="menu-span">Schedule</span>
          </div>
        </el-menu-item>
        <el-menu-item index="tasks">
          <div class="menu-item-content">
            <i class="el-icon-document icon"></i>
            <span class="menu-span">Task</span>
          </div>
        </el-menu-item>
      </el-menu>
      <!-- 数据库选择区域 -->
      <div class="database-section">
        <div id="database-head">
          <h4 class="database-title">Databases</h4>
          <el-button
            icon="el-icon-plus"
            class="icon-only-btn"
            @click="openCreateDatabaseDialog"
          ></el-button>
        </div>
        <ul class="database-list">
          <li
            v-for="(db, index) in sortedDatabases"
            :key="index"
            @click="selectDatabase(db)"
            :class="{ active: selectedDatabase === db }"
          >
            <span style="padding-left: 10px;">{{ db.name }}</span>
          </li>
        </ul>
      </div>
      <!-- 设置按钮 -->
      <div id="setting" @click="toggleSettingsDrawer">
        <i class="el-icon-setting icon"></i>
      </div>
      <div id="space-occupying"></div>
    </el-aside>

    <!-- 整个页面右侧的设置侧边栏 -->
    <settings-drawer
        v-if="selectedDatabase && selectedDatabase.name"
        :visible.sync="isSettingsDrawerVisible"
        :selectedDatabase="selectedDatabase"
        @update:visible="isSettingsDrawerVisible = $event"
        @update:name="updateDatabaseName"
        @delect:database="delectDatabase"
      />
    
    <!-- 创建数据库的弹窗 -->
    <el-dialog
      title="Create Database"
      :visible.sync="isCreateDatabaseDialogVisible"
      width="400px"
      @close="closeCreateDatabaseDialog"
    >
      <el-form :model="newDatabase" ref="createDatabaseForm" label-width="55px">
        <el-form-item label="Name" prop="name">
          <el-input
            v-model="newDatabase.name"
            placeholder="Enter database name"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-form :model="newDatabase" ref="createDatabaseForm" label-width="55px">
        <el-form-item label="Link" prop="link">
          <el-input
            v-model="subscriptionLink"
            placeholder="Enter subscription link (optional)"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeCreateDatabaseDialog">Cancel</el-button>
        <el-button type="primary" @click="createDatabase">Create</el-button>
      </span>
    </el-dialog>
  
      <!-- 主体内容区域 -->
      <el-container>
        <el-header class="header">
          <h2 style="display: inline-block;">{{ pageTitle }}</h2>
          <add-task-button 
            :selectedDate="formatDate(selectedDate)" 
            @task-added="addTask"
            style="position: absolute; left: 450px; top: 20px;"
          />
          
          <!-- 时间排序 -->
          <div class="select-container" style="right: 20px;">
            <div class="select-title">Deadline Sort</div>
            <el-select v-model="timeSortOrder" placeholder="Time Sort">
              <el-option label="Ascending" value="asc"></el-option>
              <el-option label="Descending" value="desc"></el-option>
              <el-option label="None" value="none"></el-option>
            </el-select>
          </div>

          <!-- 任务等级排序 -->
          <div class="select-container" style="right: 180px;">
            <div class="select-title">Task Level Sort</div>
            <el-select v-model="prioritySortOrder" placeholder="Priority Sort">
              <el-option label="Ascending" value="asc"></el-option>
              <el-option label="Descending" value="desc"></el-option>
              <el-option label="None" value="none"></el-option>
            </el-select>
          </div>

          <!-- 任务状态筛选 -->
          <div class="select-container" style="right: 340px;">
            <div class="select-title">Task Status</div>
            <el-select v-model="taskStatusFilter" placeholder="Task Status">
              <el-option label="Unfinished" value="0"></el-option>
              <el-option label="Done" value="1"></el-option>
              <el-option label="All" value="all"></el-option>
            </el-select>
          </div>
        </el-header>

        <!-- 任务表格 -->
      <el-table :data="sortedTasks" style="width: 72%; margin-top: 100px; margin-left: auto; margin-right: auto; text-align: center; font-size: 24px;">
        <el-table-column label="Task Title" prop="name" width="370">
          <template #default="{ row }">
            <span style="font-size: 18px; display: block; width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
              {{ row.name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="Start Time" prop="startTime" width="160">
          <template #default="{ row }">
            <span style="font-size: 18px;">{{ formatDate(row.startTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="Deadline" prop="endTime" width="160">
          <template #default="{ row }">
            <span style="font-size: 18px;">{{ formatDate(row.endTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="Task Level" prop="priority" width="160">
          <template #default="{ row }">
            <span style="font-size: 18px;">
              {{ getTaskPriority(row.priority) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="Task Status" prop="status" width="160">
          <template #default="{ row }">
            <span style="font-size: 18px;">
              {{ row.status === 0 ? 'Unfinished' : 'Done' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="Control" width="160">
          <template #default="{ row }">
            <div style="display: flex; justify-content: space-between;">
              <el-button size="mini" type="danger" @click="deleteTask(row)" style="font-size: 14px;">Delete</el-button>
              <edit-task-button 
                :selectedTask="row" 
                @task-updated="updateTask"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
  
        <!-- 分页功能 -->
        <el-pagination
          v-if="filteredTasks.length > 0"
          background
          :current-page.sync="currentPage"
          :page-size="pageSize"
          :total="filteredTasks.length"
          @current-change="handlePageChange"
          layout="prev, pager, next, jumper"
          style="text-align: center; width: 200px; margin-left: auto; margin-right: auto; margin-bottom: 250px;"
        />
      </el-container>
    </el-container>
</template>

<script>
  import locale from "element-ui/lib/locale";
  import lang from "element-ui/lib/locale/lang/en";
  import SettingsDrawer from "@/components/SettingsDrawer.vue";
  import addTask from "@/components/addTask.vue";
  import editTask from "@/components/editTask.vue";
  import { getDatabase } from "../api/getDatabase";
  import { changeDatabase } from "../api/changeDatabase";
  import { createDatabase } from "../api/createDatabase";
  import { createDatabaseWithics } from "../api/createDatabaseWithics";
  import { delDatabase } from "../api/delDatabase";
  import { getTask } from "../api/getTask";
  import { createTask } from "../api/createTask";
  import { updateTask } from "../api/updateTask";
  import { deleteTask } from "../api/deleteTask";

  locale.use(lang);

  export default {
    data() {
      return {
        selectedDate: new Date(),
        tasks: [],
        activeMenu: "tasks",
        pageTitle: "Task Management",
        isSettingsDrawerVisible: false,
        currentPage: 1,
        pageSize: 6,
        timeSortOrder: "none", // 时间排序（升序）
        prioritySortOrder: "none", // 任务等级排序（升序）
        taskStatusFilter: "all", // 任务状态筛选（所有）
        isTaskDetailVisible: false, // 控制任务详情浮窗
        currentTask: null, // 存储当前任务详情
        databases: [],
        subscriptionLink: "", // 订阅链接
        selectedDatabase: null,
        isCreateDatabaseDialogVisible: false, // 控制创建数据库弹窗的显示
        newDatabase: {name: ""}, // 新数据库信息
      };
    },
    mounted(){
      this.initData();
    },
    components: {
      SettingsDrawer,
      addTaskButton: addTask,
      editTaskButton: editTask,
    },
    computed: {
      sortedDatabases() {
        return this.databases.sort((a, b) => a.name.localeCompare(b.name));
      },
      filteredTasks() {    
        let tasks = this.tasks.slice();

        // 任务状态筛选
        if (this.taskStatusFilter !== "all") {
          tasks = tasks.filter(task => task.status === Number(this.taskStatusFilter));
        }

        // 根据时间排序
        if (this.timeSortOrder === "asc") {
          tasks.sort((a, b) => new Date(a.endTime) - new Date(b.endTime));
        } else if (this.timeSortOrder === "desc") {
          tasks.sort((a, b) => new Date(b.endTime) - new Date(a.endTime));
        } else if (this.timeSortOrder === "none") {
          tasks = [...tasks];
        }

        // 根据任务等级排序
        if (this.prioritySortOrder === "asc") {
          tasks.sort((a, b) => a.priority - b.priority);
        } else if (this.prioritySortOrder === "desc") {
          tasks.sort((a, b) => b.priority - a.priority);
        } else if (this.timeSortOrder === "none") {
          tasks = [...tasks];
        }

        return tasks;
      },
      sortedTasks() {
        const start = (this.currentPage - 1) * this.pageSize;
        const end = start + this.pageSize;
        return this.filteredTasks.slice(start, end);
      }
    },
    watch: {
      taskStatusFilter() {
        // 当筛选条件改变时，重置页码到第一页
        this.currentPage = 1;
      }
    },
    methods: {
      formatDate(date) {
        const d = new Date(date);
        return d.toLocaleDateString();
      },
      getTaskPriority(priority) {
        switch (priority) {
          case 1:
            return 'Common';
          case 2:
            return 'Minor';
          case 3:
            return 'Major';
          default:
            return 'Unknown';
        }
      },
      // 更新任务的逻辑
      async updateTask(updatedTask) {
        const formatDate = (date) => {
          const d = new Date(date);
          const year = d.getFullYear();
          const month = (d.getMonth() + 1).toString().padStart(2, '0'); 
          const day = d.getDate().toString().padStart(2, '0');
          const hours = d.getHours().toString().padStart(2, '0');
          const minutes = d.getMinutes().toString().padStart(2, '0');
          const seconds = d.getSeconds().toString().padStart(2, '0');
          return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
        };

        let Task = {
          id: updatedTask.id,
          task_Id: updatedTask.name,
          index_Id: this.selectedDatabase.name,
          start_Date: formatDate(updatedTask.startTime),
          end_Date: formatDate(updatedTask.endTime),
          priority: updatedTask.priority,
          details: updatedTask.details,
          status: updatedTask.status,
        };

        const res = await updateTask(Task);
        if (res.status === 200) {
          const taskIndex = this.tasks.findIndex(task => task.id === updatedTask.id);  // 找到对应的任务

          if (taskIndex !== -1) {
            this.tasks.splice(taskIndex, 1, updatedTask); 
          }

          this.$message.success("Task updated successfully!");
        } else {
          this.$message.error("Failed to update task!");
        }
      },

      toggleSettingsDrawer() {
        this.isSettingsDrawerVisible = !this.isSettingsDrawerVisible;
      },
      handlePageChange(page) {
        this.currentPage = page;
      },
      async deleteTask(taskToDelete) {
        this.$confirm("Are you sure the task is complete?", "Prompt", {
          confirmButtonText: "Yes",
          cancelButtonText: "No",
          type: "warning",
        })
          .then(async () => {
            const res = await deleteTask(this.selectedDatabase.name, taskToDelete.id);
            if (res.status === 200) {
              this.tasks = this.tasks.filter(task => task.name !== taskToDelete.name);  // 根据任务标题删除任务
              this.$message({
                message: `Task "${taskToDelete.name}" deleted successfully!`,
                type: "success",
              });
            } else {
              this.$message.error("Failed to delete task!");
            }
          })
          .catch(() => {
            this.$message.info("Deleted task canceled.");
          });
      },
      async initData() {
        try {
          // 使用 await 等待异步操作完成
          const res = await getDatabase();
          let sel = res.data[res.data.length-1];
          res.data.pop();
          this.databases = res.data.map((name) => ({
            name: name.endsWith('.json') ? name.replace(/\.json$/, '') : name,
          }));

          // 设置默认选中数据库
          this.selectedDatabase = this.databases.find((db) => db.name === sel) || this.databases[0];
          // 获取任务列表
          const taskRes = await getTask(this.selectedDatabase.name);


          // 将任务列表存储到 tasks 中
          this.tasks = taskRes.data.map((task) => ({
            id: task.id,
            name: task.task_Id,
            startTime: task.start_Date,
            endTime: task.end_Date,
            priority: task.priority,
            details: task.details,
            status: task.status,
          }));

          
        } catch (error) {
          console.error('Error fetching databases:', error);
          this.databases = [];
          this.selectedDatabase = null;
        }
      },
      // 更新数据库名称
      async updateDatabaseName(newName) {
        // 判断是否存在同名数据库
        if (this.databases.some((db) => db.name === newName)) {
          this.$message.error(`Database "${newName}" already exists!`);
          return;
        }
        const res = await changeDatabase(this.selectedDatabase.name, newName);
        
        if (res.status === 200) {
          // 更新数据库列表中的数据库名称
          this.databases = this.databases.map((db) => {
            if (db.name === this.selectedDatabase.name) {
              db.name = newName;
            }
            return db;
          });
          this.selectedDatabase.name = newName;
          this.$message.success(`Database name has been updated to: ${this.selectedDatabase.name}`);
        } else {
          this.$message.error("Failed to update database name!");
        }
      },
      // 删除数据库
      async delectDatabase() {
        const res = await delDatabase(this.selectedDatabase.name);
        if(res.status==200){
          this.databases = this.databases.filter((db) => db.name !== this.selectedDatabase.name);
          this.selectedDatabase = this.databases[0] || null;
          // 关闭设置侧边栏
          this.isSettingsDrawerVisible = false;
          this.$message.success("Database deleted successfully!");
        }else{
          this.$message.error("Failed to delete database!");
        }
      },
      // 打开创建数据库弹窗
      openCreateDatabaseDialog() {
        this.newDatabase.name = ""; 
        this.isCreateDatabaseDialogVisible = true;
      },
      // 关闭创建数据库弹窗
      closeCreateDatabaseDialog() {
        this.isCreateDatabaseDialogVisible = false;
      },
      // 创建数据库
      async createDatabase() {
        if (!this.newDatabase.name.trim()) {
          this.$message.error("Database name cannot be empty!");
          return;
        }
        // 判断数据库名称是否已存在
        if (this.databases.some((db) => db.name === this.newDatabase.name.trim())) {
          this.$message.error(`Database "${this.newDatabase.name}" already exists!`);
          return;
        }
        let a;
        // 判断link是否为空
        if(this.subscriptionLink.trim() === ""){
          // 使用正常的创建数据库请求
          const res = await createDatabase(this.newDatabase.name.trim());
          a = res;
        }else{
          const res = await createDatabaseWithics(this.subscriptionLink.trim() , this.newDatabase.name.trim());
          a = res;
        }
        if(a.status === 200){
          const newDb = { name: this.newDatabase.name.trim() };
          this.databases.push(newDb); // 添加到数据库列表
          this.$message.success(`Database "${newDb.name}" created successfully!`);
          this.closeCreateDatabaseDialog(); // 关闭弹窗
          this.selectedDatabase = newDb; // 选中新创建的数据库
          const res = await getTask(this.selectedDatabase.name);
          this.tasks = res.data.map((task) => ({
            id: task.id,
            name: task.task_Id,
            startTime: task.start_Date,
            endTime: task.end_Date,
            priority: task.priority,
            details: task.details,
            status: task.status,
          }));
        }else{
          this.$message.error("Failed to create database!");
        }

        this.subscriptionLink = ""; // 清空订阅链接
        

      },
      async selectDatabase(db) {
        if (this.selectedDatabase === db) {
          return;
        }
        const res = await getTask(db.name);

        this.tasks = res.data.map((task) => ({
            id: task.id,
            name: task.task_Id,
            startTime: task.start_Date,
            endTime: task.end_Date,
            priority: task.priority,
            details: task.details,
            status: task.status,
          }));
        
        this.selectedDatabase = db;
        this.$message.success(`Selected Database: ${db.name}`);
      },
      hasTask(date) {
        const formattedDate = this.formatDate(new Date(date)); // 日历中的日期
        // 判断是否存在未完成的任务
        const hasIncompleteTask = this.tasks.some((task) => {
          const taskStart = this.formatDate(new Date(task.startTime));
          const taskEnd = this.formatDate(new Date(task.endTime));
          return (
            task.status === 0 && // 未完成的任务
            formattedDate >= taskStart &&
            formattedDate <= taskEnd
          );
        });
        return hasIncompleteTask;
      },
      // 格式化日期
      formatDate(date) {
        const d = new Date(date);
        return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(
          d.getDate()
        ).padStart(2, "0")}`;
      },
      async addTask(newTask) {
        const formatDate = (date) => {
          const d = new Date(date);
          const year = d.getFullYear();
          const month = (d.getMonth() + 1).toString().padStart(2, '0'); 
          const day = d.getDate().toString().padStart(2, '0');
          const hours = d.getHours().toString().padStart(2, '0');
          const minutes = d.getMinutes().toString().padStart(2, '0');
          const seconds = d.getSeconds().toString().padStart(2, '0');
          return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
        };
        let task = {
          id: newTask.id,
          task_Id: newTask.name,
          index_Id: this.selectedDatabase.name,
          start_Date: formatDate(newTask.startTime),
          end_Date: formatDate(newTask.endTime),
          priority: newTask.priority,
          details: newTask.details,
          status: newTask.status,
        };

        let task_put = JSON.stringify(task);
        // console.log(task_put);

        // 添加任务
        const res = await createTask(task_put);
        if (res.status === 200) {
          this.tasks.push(newTask);
          this.$message.success("Task added successfully!");
        } else {
          this.$message.error("Failed to add task!");
        }
      },
      getPriorityText(priority) {
        // 将数值优先级转回文本用于展示
        const priorityText = {
          3: "Major",
          2: "Minor",
          1: "Common",
        };
        return priorityText[priority] || "Major";  
      },
      handleMenuSelect(key) {
        this.activeMenu = key;
        switch (key) {
          case "schedule":
            this.$router.push("/");
            break;
          case "tasks":
            break;
        }
      },
      showTaskDetail(task) {
        this.currentTask = task;
        this.isTaskDetailVisible = true;
      },
      // 关闭任务详情
      closeTaskDetail() {
        this.isTaskDetailVisible = false;
        this.currentTask = null;
      },
      // 标记任务为已完成
      markTaskAsCompleted(task) {
        if (task && task.status !== 1) {
          this.$confirm("Are you sure the task is complete?", "Prompt", {
            confirmButtonText: "Yes",
            cancelButtonText: "No",
            type: "warning",
          })
            .then(() => {
              task.status = 1; // 将任务状态设置为已完成
              this.$message({
                message: `Task "${task.name}" marked as completed!`,
                type: "success",
              });
              this.closeTaskDetail(); // 关闭详情弹窗

            })
            .catch(() => {
              this.$message.info("Canceled marking task as completed.");
            });
        }else{
          this.$message.error("Task has been completed!");
        }
      },
      // 获取优先级对应的 CSS 类名
      getPriorityClass(priority) {
        const classes = {
          3: "priority-major",
          2: "priority-minor",
          1: "priority-common",
        };
        return classes[priority] || "priority-major";
      },
      // 获取优先级文本
      getPriorityText(priority) {
        const priorityText = {
          3: "Major",
          2: "Minor",
          1: "Common",
        };
        return priorityText[priority] || "Major";
      }
    }
  };
</script>
  
<style scoped>
  .schedule-page {
    height: 100vh;
    display: flex;
    overflow: hidden;
  }
  
  .aside {
    background-color: #f4f5f7;
    padding-top: 20px;
    text-align: center;
    border-right: 1px solid #dcdfe6;
  }
  
  .profile {
    margin-bottom: 20px;
  }
  
  .main-content {
    padding: 20px;
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }
  
  .select-container {
    position: absolute;
    top: 10px;
  }

  .select-title {
    font-size: 14px;
    color: #606266;
    margin-bottom: 5px;
  }
  
  .el-select {
    width: 150px;
  }
  
  .completed {
    text-decoration: line-through;
    color: #c0c4cc;
  }
  
  .el-pagination {
    margin-top: 20px;
    text-align: center;
    margin-bottom: 30px;
    margin-left: -50px;
  }
  
  #setting {
    /* 固定在底部 */
    position: absolute;
    width: 184px;
    bottom: 40px;
    font-size: 50px !important;
    text-align: center;
    color: #909399;
    cursor: pointer;
    background-color: #f4f5f7;
  }
  #space-occupying {
    position: absolute;
    width: 184px;
    bottom: 0;
    height: 40px;
    background-color: #f4f5f7;
  }
  
  i.el-icon-setting.icon::before {
    font-size: 40px;
  }
  
  #setting:hover {
    color: #5a9cf8;
  }

  task-list {
    width: 100%;
    height: 100%;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    padding: 20px;
    background-color: #ffffff;
    display: flex;
    flex-direction: column;
    overflow: hidden; 
  }

  .tasks {
    list-style: none;
    padding: 0;
    overflow-y: auto;
    flex: 1;
    margin-bottom: 0 !important;
  }

  .tasks li {
    display: flex;
    align-items: center;
    margin: 10px 0;
  }

  .completed {
    text-decoration: line-through;
    color: #c0c4cc;
  }

  .menu-item-content {
    background-color: #f4f5f7;
    display: flex;
    justify-content: flex-start;
    align-items: center; 
    height: 100%;
    padding-left: 35px; 
  }

  .el-menu-item {
    margin-right: 0 !important;
    height: 70px;
    text-align: center;
    padding: 0;
  }

  .el-menu-item [class^=el-icon-] {
    margin-right: 0 !important;
    font-size: 30px;
  }

  .icon {
    font-size: 24px;
    margin-bottom: 5px;
  }

  .el-menu-item, .el-submenu__title {
    line-height: 10px !important;
  }

  li.el-menu-item {
    padding-left: 0 !important;
    height: 90px !important;
  }

  .menu-span {
    font-size: 18px;
    padding-left: 15px;
  }

   /* 数据库选择样式 */
   .database-section {
    margin-top: 60px;
    padding-top: 20px;
    padding-bottom: 10px;
    text-align: left;
  }

  .database-title {
    font-size: 14px;
    color: #909399;
    padding: 0 20px;
    margin-bottom: 10px;
  }

  .database-list {
    margin-top: 20px;
    padding: 0 10px;
    list-style: none; 
    max-height: 380px; 
    overflow-y: auto;
    border-radius: 8px; 
  }

  .database-list li {
    display: block; 
    padding: 10px 15px;
    cursor: pointer;
    color: #606266;
    font-size: 14px; 
    line-height: 1.5; 
    transition: background-color 0.2s ease, color 0.2s ease;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis; 
  }


  .database-list li:hover {
    background-color: #f5f7fa;
    border-radius: 8px; 
  }

  .database-list li.active {
    background-color: #e6f7ff; 
    border-radius: 8px; 
    font-weight: bold; 
    color: #409eff;
  }

  .database-list::-webkit-scrollbar {
    width: 8px;
  }

  .database-list::-webkit-scrollbar-thumb {
    background-color: #888; 
    border-radius: 4px; 
  }

  .database-list::-webkit-scrollbar-thumb:hover {
    background-color: #555; 
  }
  .database-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
  }

  .icon-only-btn {
    background-color: transparent;
    color: #909399;
    border: none;
    padding: 0;
    margin-top: 8px;
    margin-right: 10px;
    font-size: 18px;
    cursor: pointer;
    transition: color 0.3s ease;
  }

  .icon-only-btn:hover {
    color: #409eff;
  }
  #database-head{
    display: flex;
    justify-content: space-between;
    align-items: center;

  }

  /* 侧边栏 */
  .settings-drawer {
    width: 400px;
  }
  </style>